import React, { PureComponent } from 'react'
import { PageContainer } from '@ant-design/pro-layout';
import { Table, Card, Button, Form, Input, Pagination, message, Modal, Cascader, Row, Col, Select } from 'antd';
import StudentTypeCascader from '../Components/StudentTypeCascader/index';
import { getExamAnalyze, deleteExamAnalyze } from '../../services/learn'
import Authorized from '../../components/Authorized/Authorized'
import { baseurl } from '../../services/baseurl'
import { selectTest } from '@/services/paperInfo'
import { getSubject } from '@/services/lessons'
export default class Learn extends PureComponent<any, any> {
    constructor(props: any) {
        super(props)
        const name = this.props.location.query.name;
        const stydent_type_data = JSON.parse(localStorage.getItem('userinfo')).student_type;
        const student_type = stydent_type_data ? stydent_type_data.split(',').map(Number) : [];
        this.state = {
            comprehensive: false,
            student_type,
            data: [],
            currentPage: '1',
            count: 1,
            row: {},
            name: name || '',
            test_name: '',
            id_number: '',
            selectedRowKeys: [],
            options: [],
            currentComprehensive: {},
            showComprehensive: false,
            subject: '',
            is_sw: '2'
        }
    }
    changeStudentType = (e: any) => {
        if (!e[0]) return;
        this.setState({
            student_type: e
        })
    }
    renderList = (page: any, is_sw) => {
        const { student_type, name, id_number, test_name, subject } = this.state;
        getExamAnalyze({ page, student_type, name, id_number, test_name, subject, is_sw }).then(res => {
            this.setState({
                data: res.data,
                count: res.count
            })
        })
    }
    componentDidMount() {
        this.renderList('1', '2')
        getSubject().then(res => {
            if (!res || !res[0]) return;
            let data = JSON.stringify(res);
            data = data
                .replace(/id/g, 'value')
                .replace(/title/g, 'label')
                .replace(/pvalue/g, 'pid')
                .replace(/,"pid"/g, ',"isLeaf":false,"pid"')
                .replace(/,"children":\[\]/g, '')
            this.setState({
                options: JSON.parse(data),
            });
        })
    }
    changeIsSw = (e: any) => {
        this.setState({
            is_sw: e,
            currentPage: 1
        })
        this.renderList('1', e);
    }
    changePage = (e: any) => {
        const { is_sw } = this.state;
        this.renderList(e, is_sw);
        this.setState({
            currentPage: e
        })
    }
    changeValue = (e: any, name: string) => {
        this.setState({
            [name]: e.target.value
        })
    }
    searchHandle = () => {
        const { is_sw } = this.state;
        this.renderList('1', is_sw);
        this.setState({
            currentPage: 1
        })
    }
    deleteHandle = () => {
        const { selectedRowKeys, is_sw } = this.state;
        Modal.confirm({
            title: '提示',
            content: '确定删除选中项？',
            onOk: () => {
                deleteExamAnalyze({ id: selectedRowKeys }).then(res => {
                    if (res.status === 1) {
                        message.success('已删除')
                        this.setState({
                            selectedRowKeys: []
                        })
                        this.renderList('1', is_sw)
                    } else {
                        message.error('删除失败')
                    }
                })
            }
        })

    }
    exportHandle = () => {
        const { student_type, name, id_number, names, subject } = this.state;

        Modal.confirm({
            title: '提示',
            content: '确定导出用户？',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                window.open(`${baseurl}index/index/topic_statis_derive?names=&subject=${subject[subject.length - 1] || ''}&student_type=${student_type[student_type.length - 1] || ''}&name=${name}&id_number=${id_number}`)
            }
        })
    }
    changeSubject = (e, d) => {
        if (!e[0]) {
            return this.setState({
                test_name: '',
                subject: ''
            })
        };
        if (e[1]) {
            this.setState({
                subject: e[e.length - 1],
                test_name: ''
            })
        }
        if (e[2]) {
            this.setState({
                test_name: e[e.length - 1],
                subject: ''
            })
        } else {
            this.setState({
                test_name: '',
            })
        }

    }
    loadData = selectedOptions => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        selectTest({ subject: targetOption.value }).then(res => {
            if (!res || !res[0]) return;
            let data = JSON.stringify(res);
            data = data
                .replace(/id/g, 'value')
                .replace(/name/g, 'label')
            targetOption.children = JSON.parse(data)
            this.setState({
                options: [...this.state.options],
            });
        })
    };
    showComprehensive = (row) => () => {
        this.setState({
            currentComprehensive: row,
            showComprehensive: true
        })
    }
    hideComprehensive = () => {
        this.setState({
            showComprehensive: false
        })
    }
    showDetails = () => {
        const { currentComprehensive, is_sw } = this.state;
        this.setState({
            showComprehensive: false,
            id_number: currentComprehensive.id_number,
            currentPage: 1
        }, () => {
            this.renderList(1, is_sw)
        })

    }
    render() {
        const { student_type, data, count, name, selectedRowKeys, options, showComprehensive, currentComprehensive, id_number, currentPage } = this.state;
        const columns = [
            {
                title: '考试名称',
                dataIndex: 'names',
                render: (names: string) => {
                    return names.replace('\\','')
                }
            },
            {
                title: '姓名',
                dataIndex: 'name'
            },
            {
                title: '准考证号',
                dataIndex: 'id_number'
            },
            {
                title: '单位部门',
                dataIndex: 'student_types',
                render: (student_types: string) => {
                    return student_types 
                }
            },
            {
                title: '分数',
                dataIndex: 'grade',
            },
            {
                title: '答题时长',
                dataIndex: 'duration',
                render: (duration: any) => {
                    return (duration / 60 / 1000).toFixed(2) + '分钟'
                }
            },
            {
                title: '答题时间',
                dataIndex: 'time',
            },
            {
                title: '操作',
                dataIndex: 'id',
                render: (id: any, row: any) => {
                    return <a onClick={this.showComprehensive(row)}>综合成绩</a>
                }
            }
        ]
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys: any) => {
                this.setState({
                    selectedRowKeys,
                })
            },
        };
        return (
            <PageContainer>
                <Card>
                    <div style={{ overflow: 'hidden', marginBottom: 20 }}>
                        <Form style={{ float: 'right' }} layout="inline">
                            <Form.Item>
                                <Select onChange={this.changeIsSw} defaultValue="2">
                                    <Select.Option key="2" value="2">特种设备</Select.Option>
                                    <Select.Option key="1" value="1">特种作业</Select.Option>
                                </Select>
                            </Form.Item>
                            <Form.Item><StudentTypeCascader onChange={this.changeStudentType} value={student_type} /></Form.Item>
                            <Form.Item><Cascader
                                onChange={this.changeSubject}
                                loadData={this.loadData}
                                options={options}
                                changeOnSelect
                                placeholder="请选择科目"
                            /></Form.Item>
                            <Form.Item><Input placeholder="请输入姓名" value={name} onChange={(e: any) => this.changeValue(e, 'name')} /></Form.Item>
                            <Form.Item><Input placeholder="请输入准考证号" onChange={(e: any) => this.changeValue(e, 'id_number')} value={id_number} /></Form.Item>
                            <Form.Item><Button type="primary" onClick={this.searchHandle}>搜索</Button></Form.Item>
                            <Form.Item><Button type="primary" danger onClick={this.exportHandle}>导出</Button></Form.Item>
                        </Form>
                    </div>
                    <Table
                        scroll={{ x: 1400 }}
                        footer={() => <Authorized authority={[602]}><Button type="primary" danger onClick={this.deleteHandle}>删除选中</Button></Authorized>}
                        rowSelection={rowSelection} columns={columns} pagination={false}
                        dataSource={data} rowKey="ids"></Table>
                    <Pagination style={{ float: 'right', marginTop: 20 }} onChange={this.changePage} current={currentPage * 1} total={count} showQuickJumper showTotal={(total, range) => `第${range[0]}条-第${range[1]}条，共 ${total} 条`} />
                </Card>
                <Modal title="综合成绩" visible={showComprehensive} onCancel={this.hideComprehensive} footer={[<Button type="primary" key="1" onClick={this.hideComprehensive}>确定</Button>]}>
                    <Row>
                        <Col span={6}><h4>模拟次数</h4></Col>
                        <Col span={18}><h4>{currentComprehensive.num || 0}次</h4></Col>
                        <Col span={6}><h4>完成率</h4></Col>
                        <Col span={18}><h4>{currentComprehensive.total || 0}%</h4></Col>
                        <Col span={6}><h4>正确率</h4></Col>
                        <Col span={18}><h4>{currentComprehensive.correct_total || 0}%</h4></Col>
                    </Row>
                    <Button type="primary" onClick={this.showDetails}>模拟明细</Button>
                </Modal>
            </PageContainer>
        )
    }
}
